package com.yyh.photo.controller;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import com.alibaba.fastjson2.JSONObject;
import com.yyh.photo.common.R;
import com.yyh.photo.common.ResultCodeEnum;
import com.yyh.photo.domain.CommodityDomain;
import com.yyh.photo.entity.CommodityEntity;
import com.yyh.photo.service.CommodityService;
import com.yyh.photo.utils.HttpClientUtils;
import com.yyh.photo.utils.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import javax.servlet.http.HttpServletResponse;


/**
 * @author jxjk.safe
 * @date 2023-06-07 17:15:10
 */
@Slf4j
@RestController
@RequestMapping("/system/commodity")
@Api(description = "管理", tags = "commodity控制器")
public class CommodityController {
    @Autowired
    private CommodityService commodityService;

    @ApiOperation(value = "分页查询")
    @PostMapping("/page/list")
    public R pageList(@ApiParam(name = "commodityDomain", value = "查询对象", required = false) @RequestBody CommodityDomain commodityDomain) {
        if (commodityDomain.getPageNum() == null) {
            return R.error().code(ResultCodeEnum.PARAM_ERROR.getCode()).message("分页参数page不能为空！");
        }
        if (commodityDomain.getPageSize() == null) {
            return R.error().code(ResultCodeEnum.PARAM_ERROR.getCode()).message("分页参数pageSize不能为空！");
        }
        if (commodityDomain.getPageNum() < 0 || commodityDomain.getPageSize() < 0) {
            return R.error().code(ResultCodeEnum.PARAM_ERROR.getCode()).message("分页参数不能为负数！");
        }

        Page<CommodityDomain> page = new Page<>(commodityDomain.getPageNum(), commodityDomain.getPageSize());
        List<CommodityDomain> dataList = commodityService.pageQuery(page, commodityDomain);

        return R.ok().data("total", page.getTotal()).data(dataList);
    }

    @ApiOperation(value = "不分页查询")
    @PostMapping(" /list")
    public R list(@ApiParam(name = "commodityDomain", value = "查询对象", required = false) @RequestBody CommodityDomain commodityDomain) {


        List<CommodityDomain> dataList = commodityService.getlist(commodityDomain);

        return R.ok().data(dataList);
    }

    @ApiOperation(value = "查询详细信息")
    @GetMapping("/info/{id}")
    public R info(@ApiParam(name = "id", value = "主键", required = true) @PathVariable("id") Integer id) {
        if (id == null) {
            return R.error().code(ResultCodeEnum.PARAM_ERROR.getCode()).message("主键信息不能为空!");
        }
        try {
            CommodityDomain commodity = commodityService.getDetailById(id);
            return R.ok().data(commodity);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return R.error().code(ResultCodeEnum.UNKNOW_REASON.getCode()).message("查询详细信息失败!");
        }
    }

    @ApiOperation(value = "新增信息")
    @PostMapping("/add")
    public R save(@ApiParam(name = "commodityEntity", value = "commodityEntity 对象", required = false) @RequestBody CommodityDomain commodityEntity) {
        if (commodityEntity == null) {
            return R.error().code(ResultCodeEnum.PARAM_ERROR.getCode()).message("保存的信息对象不能为空！");
        }
        try {
            boolean b = commodityService.saveCommodity(commodityEntity);
            if (b) {
                return R.ok();
            } else {
                return R.error().code(ResultCodeEnum.UNKNOW_REASON.getCode()).message("保存信息失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCodeEnum.UNKNOW_REASON.getCode()).message("保存信息失败！");
        }
    }

    @ApiOperation(value = "修改信息")
    @PutMapping("/update")
    public R update(@ApiParam(name = "commodityEntity", value = "commodityEntity 对象", required = false) @RequestBody CommodityEntity commodityEntity) {
        if (commodityEntity == null) {
            return R.error().code(ResultCodeEnum.PARAM_ERROR.getCode()).message("保存的信息对象不能为空！");
        }
        try {
            boolean b = commodityService.updateById(commodityEntity);
            if (b) {
                return R.ok();
            } else {
                return R.error().code(ResultCodeEnum.UNKNOW_REASON.getCode()).message("修改信息失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCodeEnum.UNKNOW_REASON.getCode()).message("修改信息失败！");
        }
    }

    @ApiOperation(value = "删除信息")
    @DeleteMapping("/delete/{id}")
    public R delete(@ApiParam(name = "id", value = "主键", required = true) @PathVariable("id") Integer id) {
        if (id == null) {
            return R.error().code(ResultCodeEnum.PARAM_ERROR.getCode()).message("主键信息不能为空!");
        }
        boolean b = commodityService.removeById(id);
        if (b) {
            return R.ok().message("删除成功");
        } else {
            return R.error().code(ResultCodeEnum.UNKNOW_REASON.getCode()).message("删除信息失败！");
        }
    }

    @ApiOperation(value = "根据code  获取用户信息")
    @GetMapping("/getAccessToken/{code}")
    public R getAccessToken(@ApiParam(name = "code", value = "code", required = true) @PathVariable("code") String code) throws Exception {
        JSONObject js = ImageUtils.getAccessToken(code);
        if (js.containsKey("errcode")) {
            return R.error().data(js.getString("errmsg"));
        }
        return R.ok().data(js);
    }

    @RequestMapping("/getCode")
    public void createQRCode(String param, String page, int width, HttpServletResponse response) throws Exception {
        String token = ImageUtils.postToken();
        URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + token);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        httpURLConnection.setRequestMethod("POST");// 提交模式

// conn.setConnectTimeout(10000);//连接超时 单位毫秒

// conn.setReadTimeout(2000);//读取超时 单位毫秒

// 发送POST请求必须设置如下两行

        httpURLConnection.setDoOutput(true);

        httpURLConnection.setDoInput(true);

        // 获取URLConnection对象对应的输出流

        PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());

        // 发送请求参数

        JSONObject paramJson = new JSONObject();

      paramJson.put("scene","2");//这就是你二维码里携带的参数 String型 名称不可变

        paramJson.put("path", page); //这是设置扫描二维码后跳转的页面

        paramJson.put("width", width);

//      paramJson.put("is_hyaline", true);

//      paramJson.put("auto_color", true);

        System.out.println("httpURLConnection" + httpURLConnection);

        System.out.println("paramJson.toString()" + paramJson.toString());

        printWriter.write(paramJson.toString());

        // flush输出流的缓冲

        printWriter.flush();

        //开始获取数据

        BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
//        File file = new File(codeUrl);
//        if(file.exists()){
//            file.createNewFile();
//        }
//        OutputStream os = new FileOutputStream(new File(codeUrl));
//
        int len;
//
//        byte[] arr = new byte[1024];
//
//        while ((len = bis.read(arr)) != -1) {
//
//            os.write(arr, 0, len);
//
//            os.flush();
//
//        }
//
//        os.flush();
//
//        os.close();

        response.setContentType("image/png");

        response.setHeader("Pragma", "no-cache");

        response.setHeader("Cache-Control", "no-cache");

        response.setDateHeader("Expires", 0);

        OutputStream stream = response.getOutputStream();

        byte[] arr1 = new byte[1024];

        while ((len = bis.read(arr1)) != -1) {

            stream.write(arr1, 0, len);

            stream.flush();

        }

        stream.flush();

        stream.close();
    }

}
